package com.ikas.ai.server.config.doris;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@EnableConfigurationProperties(value = {DorisProperties.class})
@Configuration
@MapperScan(value = {"com.ikas.ai.server.module.*.dorisDao"}, sqlSessionFactoryRef = "DorisSqlSessionFactory")
@Slf4j
public class DorisConfig {
    private static final String DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver";
    private static final String MAPPER_LOCATION = "classpath:mybatis/doris/mapper/*.xml";
    private static final String VALIDATE_QUERY = "select server_status()";
    private static final String TYPE_ALIASES_PACKAGE = "com.ikas.ai.server.module.*.model";

    @Autowired
    private DorisProperties dorisProperties;

    /**
     * 创建数据源
     *
     * @return
     * @throws Exception
     */
    @Bean(name = "DorisDataSource")
    public DataSource dorisDataSource() throws Exception {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(DRIVER_CLASS_NAME);
        dataSource.setUrl(dorisProperties.getHost());
        dataSource.setPassword(dorisProperties.getDbPassword());
        dataSource.setUsername(dorisProperties.getUserName());
        dataSource.setInitialSize(dorisProperties.getInitSize());
        dataSource.setMinIdle(dorisProperties.getMinIdleSize());
        dataSource.setMaxActive(dorisProperties.getMaxActiveSize());
        dataSource.setMaxWait(dorisProperties.getMaxWait());
        dataSource.setValidationQuery(VALIDATE_QUERY);
        log.info("初始化doris数据源成功:{}", dorisProperties.getHost());
        return dataSource;
    }

    /**
     * 创建事务管理器
     *
     * @param dataSource
     * @return
     */
    @Bean(name = "DorisTransactionManager")
    public DataSourceTransactionManager dorisTransactionManager(@Qualifier("DorisDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 创建session factory
     *
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean(name = "DorisSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("DorisDataSource") DataSource dataSource) throws Exception {
        final MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        org.springframework.core.io.Resource[] resources = new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION);
        sessionFactory.setMapperLocations(resources);
        sessionFactory.setTypeAliasesPackage(TYPE_ALIASES_PACKAGE);
        sessionFactory.setConfiguration(createConfiguration());

        GlobalConfig globalConfig = GlobalConfigUtils.defaults();
        GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
        globalConfig.setDbConfig(dbConfig);
        globalConfig.setSqlInjector(new EasySqlInjector());
        sessionFactory.setGlobalConfig(globalConfig);

        return sessionFactory.getObject();
    }

    /**
     * 创建 mybatis配置
     *
     * @return
     */
    private MybatisConfiguration createConfiguration() {
        MybatisConfiguration mybatisConfiguration = new MybatisConfiguration();
        mybatisConfiguration.setMapUnderscoreToCamelCase(true);
        mybatisConfiguration.setCallSettersOnNulls(true);
//        mybatisConfiguration.setLogImpl(StdOutImpl.class);
        return mybatisConfiguration;
    }

    @Bean("DorisSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("DorisSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public EasySqlInjector easySqlInjector() {
        return new EasySqlInjector();
    }
}
